package router

import (
	"article/handler"
	"article/pkg"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

func Router() *gin.Engine {
	// 1.创建路由
	r := gin.Default()
	r.Use(Cors()) //默认跨域
	r.Static("/static", "./static")
	r.POST("/login", handler.Login)
	r.GET("/list", handler.List)
	r.GET("/detail", handler.Detail)

	r.POST("/info", MiddleWare(), handler.Info)

	r.GET("/userArticle", handler.UserArticle)
	r.GET("/ua", handler.UA)
	r.POST("/register", handler.Register)

	return r
}

func MiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.Request.Header.Get("token")
		if tokenString == "" {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "不能为空",
			})
			c.Abort()
		}
		token, err := pkg.GetToken(tokenString)
		if err != "" {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "失败",
			})
			c.Abort()
		}
		log.Println(token)
		fmt.Println("中间件开始执行了", token)
		// 设置变量到Context的key中，可以通过Get()取
		c.Set("uid", token["uid"])
		fmt.Println(token["uid"])
		// 执行函数
		c.Next()
	}
}

func Cors() gin.HandlerFunc {

	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
			c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
			c.Header("Access-Control-Allow-Credentials", "true")
			c.Set("content-type", "application/json")
		}
		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}
